<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\common\model;

use think\facade\Cache;
use think\Model;

/**
 * 分类模型
 *
 * @property int               id
 * @property int               view_count
 * @property string            title
 * @property \think\Collection follow_users
 * @property int               pid
 */
class Category extends Model{

	/**
	 * @var int
	 */
	protected $defaultSoftDelete = 0;

	/**
	 * 缓存数据的key
	 */
	const CACHE_KEY = '__category_data__';

	/**
	 * 缓存列表
	 *
	 * @var array
	 */
	private static $CACHE_NAME_ID_LIST = null;

	/**
	 * 模型初始化
	 */
	protected static function init(){
		$callback = function(){
			Cache::rm(self::CACHE_KEY);
		};
		self::afterWrite($callback);
		self::afterDelete($callback);
	}

	/**
	 * 根据分类标识获取分类ID
	 *
	 * @param string $name
	 * @return int
	 */
	public static function getIdByName($name){
		if(is_null(self::$CACHE_NAME_ID_LIST)){
			if(Cache::has(self::CACHE_KEY)){
				$data = Cache::get(self::CACHE_KEY);
			}

			if(empty($data)){
				$data = self::column('id', 'name');
			}

			if(empty($data)){
				self::$CACHE_NAME_ID_LIST = [];
			}else{
				Cache::set(self::CACHE_KEY, $data);
				self::$CACHE_NAME_ID_LIST = $data;
			}
		}

		return self::$CACHE_NAME_ID_LIST[$name] ?? 0;
	}

	/**
	 * 关联文章
	 *
	 * @return \think\model\relation\HasMany
	 */
	public function posts(){
		return $this->hasMany('Post');
	}

	/**
	 * 管理用户
	 *
	 * @return \think\model\relation\BelongsToMany
	 */
	public function followUsers(){
		return $this->belongsToMany('User', 'Collect', 'uid', 'topic_id');
	}

}
